<template>
  <z-modal
    :width="modalWidth"
    :visible="visible"
    :title="title"
    destroyOnClose
    switchFullscreen
    @ok="handleSubmit"
    @cancel="close"
    cancelText="关闭"
  >
    <a-row :gutter="10" class="warp">
      <a-col :md="6" :sm="24" class="visible-lg-block">
        <a-card :bordered="false" :bodyStyle="{maxHeight:'600px',overflow: 'auto'}">
          <!--组织机构-->
          <a-tree
            selectable
            :selectedKeys="selectedDepIds"
            :checkStrictly="true"
            :dropdownStyle="{maxHeight:'200px',overflow:'auto'}"
            :replaceFields="{title:'deptName', key:'id'}"
            :treeData="departTree"
            :expandAction="false"
            @select="onDepSelect"
            :expandedKeys.sync="expandedKeys"
          />
        </a-card>
      </a-col>
      <a-col :md="18" :sm="24">
        <a-card :bordered="false">
          <a-form @keyup.enter.native="searchQuery">
            <a-row :gutter="24">
              <a-col :span="10">
                <a-form-item label="用户账号" :label-col="labelCol" :wrapper-col="wrapperCol">
                  <a-input-search placeholder="请输入账号" v-model="queryParam.username" @search="searchQuery" />
                </a-form-item>
              </a-col>
              <a-col :span="10">
                <a-form-item label="用户姓名" :label-col="labelCol" :wrapper-col="wrapperCol">
                  <a-input-search placeholder="请输入姓名" v-model="queryParam.nickname" @search="searchQuery"/>
                </a-form-item>
              </a-col>
              <a-col :span="4">
                <a-form-item>
                  <a-button type="primary" icon="reload" style="margin-left: 8px" @click="searchReset()">重置</a-button>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
          <!--用户列表-->
          <vxe-grid
            id="userByDeptList"
            ref="vxeTable"
            :toolbarConfig="false"
            :checkbox-config="{trigger:this.multi?'row':'cell'}"
            :radio-config="{trigger:!this.multi?'row':'cell'}"
            :rowConfig="{ keyField: 'username',isCurrent:true }"
            v-bind="gridOptions"
            v-on="listeners"
            @radio-change="onRadioSelectChange"
          >
          </vxe-grid>
        </a-card>
      </a-col>
    </a-row>
  </z-modal>
</template>

<script>
import { userList, deptTree, deptUserWithin } from '@/services/system'
import VxeTableListMixin from '@/mixins/VxeTableListMixin'
import { Tree as ATree } from 'ant-design-vue'
import Criteria from '@/utils/criteria'
import { OPERATOR } from '@/store/mutation-types'
export default {
  name: 'ZSelectUserByDepModal',
  components: { ATree },
  mixins: [VxeTableListMixin],
  props: {
    modalWidth: {
      type: Number,
      default: 1250,
      required: false
    },
    multi: {
      type: Boolean,
      default: true,
      required: false
    },
    userIds: String
  },
  data() {
    return {
      columns: [
        { type: this.multi ? 'checkbox' : 'radio', width: 40 },
        { type: 'seq', width: 40 },
        { title: '用户账号', field: 'username' },
        { title: '用户姓名', field: 'nickname' },
        { title: '是否有效', field: 'accountNonLocked', slots: { default: ({ row }) => {
          return row.accountNonLocked ? '是' : '否'
        } }}
      ],
      title: '根据部门选择用户',
      selectedDepIds: [],
      departTree: [],
      visible: false,
      form: this.$form.createForm(this),
      loading: false,
      expandedKeys: []
    }
  },
  watch: {
    userIds: {
      immediate: true,
      handler() {
        this.initUserNames()
      }
    }
  },
  mounted() {
    // this.loadData()
  },
  methods: {
    initUserNames() {
      if (this.userIds) {
        const values = this.userIds.split(',')
        const queryParam = new Criteria()
        queryParam.addCriterion('username', OPERATOR.IN, values)
        var param = Object.assign({}, { criteria: queryParam.getEncode() })
        // param.pageNo = this.ipagination.currentPage
        param.pageNo = 1
        param.pageSize = values.length
        userList(param).then((res) => {
          if (res.success) {
            const selectedRowKeys = []
            const realNames = []
            this.selectionRows = []
            res.result.content.forEach(user => {
              realNames.push(user['nickname'])
              selectedRowKeys.push(user['username'])
              this.selectionRows.push(user)
            })
            this.selectedRowKeys = selectedRowKeys
            this.$emit('initComp', realNames.join(','))
          }
        })
      } else {
        this.$emit('initComp', '')
      }
    },
    async loadTableData() {
      this.loading = true
      var params = this.getQueryParams()// 查询条件
      let res
      if (this.selectedDepIds && this.selectedDepIds.length > 0) {
        res = await this.initQueryUserByDepId(this.selectedDepIds, params)
      } else {
        res = await userList(params)
      }
      this.loading = false
      return res
    },
    // async loadData(arg) {
    //   if (arg === 1) {
    //     this.ipagination.current = 1
    //   }
    //   if (this.selectedDepIds && this.selectedDepIds.length > 0) {
    //     await this.initQueryUserByDepId(this.selectedDepIds)
    //   } else {
    //     this.loading = true
    //     const params = this.getQueryParams()// 查询条件
    //     await userList(params).then((res) => {
    //       if (res.success) {
    //         this.dataSource = res.result.content
    //         this.ipagination.total = res.result.totalElements
    //       }
    //     }).finally(() => {
    //       this.loading = false
    //     })
    //   }
    // },
    showModal() {
      this.visible = true
      this.selectedDepIds = []
      this.queryDepartTree()
      this.initUserNames()
      this.loadData()
      this.form.resetFields()
    },
    close() {
      this.searchReset(0)
      this.visible = false
    },
    handleSubmit() {
      this.$emit('ok', this.selectionRows, this.selectedRowKeys)
      this.searchReset(0)
      this.close()
    },
    // 点击树节点,筛选出对应的用户
    onDepSelect(selectedDepIds) {
      if (selectedDepIds[0] != null) {
        // this.initQueryUserByDepId(selectedDepIds) // 调用方法根据选选择的id查询用户信息
        if (this.selectedDepIds[0] !== selectedDepIds[0]) {
          this.selectedDepIds = [selectedDepIds[0]]
        }
        this.loadData('reload')
      }
    },
    // 根据选择的id来查询用户信息
    initQueryUserByDepId(selectedDepIds, params) {
      return deptUserWithin(selectedDepIds.toString(), params)
    },
    queryDepartTree() {
      deptTree().then(res => {
        if (res.success) {
          this.departTree = res.result
          this.expandedKeys = this.departTree.map(item => item.id)// 默认展开父节点
        }
      })
    },
    modalFormOk() {
      this.loadData()
    },
    searchQuery() {
      this.loadData('reload')
      // if (this.selectedDepIds.length > 0) {
      //   this.initQueryUserByDepId(this.selectedDepIds)
      // } else {
      //   this.loadData(1)
      // }
    },
    onRadioSelectChange({ row }) {
      this.selectionRows = [row]
      this.selectedRowKeys = [row.username]
    }
  }
}
</script>

<style scoped lang="less">
  .warp{
    background-color:@layout-body-background;
    padding: 10px; margin: -10px;
  }
</style>
